package com.javaweb.dao.impl;

import com.javaweb.aop.NPECatch;
import com.javaweb.dao.RoleDao;
import com.javaweb.model.Permission;
import com.javaweb.model.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @author: hjm
 * @date: 2024/9/24 22:44
 */

@Repository
@Slf4j
public class RoleDaoImpl implements RoleDao {
    @Autowired
    private Connection conn;

    @Override
    @NPECatch
    public Integer insert(Role role) {
        String sql = "INSERT INTO tb_role (name) VALUES (?)";
        try (PreparedStatement ps = this.conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, role.getName());
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        return generatedKeys.getInt(1);
                    }
                }
            }
        } catch (SQLException e) {
            log.error("execute insert role error: " + e.getMessage());
        }
        return 0;
    }

    @Override
    @NPECatch
    public Integer insertRolePerm(Role role, Permission perm) {
        String sql = "INSERT INTO tb_role_per (role_id, per_id) VALUES (?, ?)";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, role.getRoleId());
            ps.setInt(2, perm.getPerId());
            return ps.executeUpdate();
        } catch (SQLException e) {
            log.error("execute insertRolePerm error: " + e.getMessage());
        }
        return 0;
    }

    @Override
    @NPECatch
    public List<Role> selectRolesByUserName(String username) {
        String sql = "SELECT r.role_id, r.name FROM tb_role r " +
                "JOIN tb_user_role ur ON r.role_id = ur.role_id " +
                "JOIN tb_user u ON u.user_id = ur.user_id " +
                "WHERE u.name = ?";
        List<Role> roles = new ArrayList<>();
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                roles.add(new Role()
                        .setRoleId(rs.getInt(1))
                        .setName(rs.getString(2)));
            }
        } catch (SQLException e) {
            log.error("execute selectRolesByUserName error: " + e.getMessage());
        }
        return roles;
    }

    @Override
    @NPECatch
    public List<Role> selectRolesByUserId(int userId) {
        String sql = "SELECT r.role_id, r.name FROM tb_role r " +
                "JOIN tb_user_role ur ON r.role_id = ur.role_id " +
                "WHERE ur.user_id = ?";
        List<Role> roles = new ArrayList<>();
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                roles.add(new Role()
                        .setRoleId(rs.getInt(1))
                        .setName(rs.getString(2)));
            }
        } catch (SQLException e) {
            log.error("execute selectRolesByUserId error: " + e.getMessage());
        }
        return roles;
    }

    @Override
    @NPECatch
    public void deleteByRoleId(int roleId) {
        String sql = "DELETE FROM tb_role WHERE role_id = ?";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, roleId);
            ps.executeUpdate();
        } catch (SQLException e) {
            log.error("execute deleteByRoleId error: " + e.getMessage());
        }
    }

    @Override
    @NPECatch
    public void deleteUserRole(int userId, int roleId) {
        String sql = "DELETE FROM tb_user_role WHERE user_id = ? AND role_id = ?";
        try (PreparedStatement ps = this.conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setInt(2, roleId);
            ps.executeUpdate();
        } catch (SQLException e) {
            log.error("execute deleteUserRole error: " + e.getMessage());
        }
    }
}
